package com.tl.boot.common.utils;

import java.security.MessageDigest;

/**
 * com.tl.boot.common.utils -- MD5Util
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/11 9:31
 */
public class MD5Util {

    public static String encode(String srcStr) {
        return processEncode(srcStr, DigitType.LOWER32);
    }

    public static String encode(String srcStr, String salt) {
        return processEncode(srcStr + salt, DigitType.LOWER32);
    }

    public static String encode(String srcStr, DigitType digitType) {
        return processEncode(srcStr, digitType);
    }

    public static String encode(String srcStr, String salt, DigitType digitType) {
        return processEncode(srcStr + salt, digitType);
    }

    private static String processEncode(String srcStr, DigitType digitType) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            String hexValue = BytesUtil.byte2hex(md5.digest(srcStr.getBytes("UTF-8")));

            switch (digitType) {
                case LOWER16:
                    return hexValue.substring(8, 24).toLowerCase();
                case UPPER16:
                    return hexValue.toUpperCase().substring(8, 24);
                case LOWER32:
                    return hexValue.toLowerCase();
                case UPPER32:
                    return hexValue.toUpperCase();
                default:
                    return hexValue.toLowerCase();
            }
        } catch (Exception e) {
            return null;
        }
    }

    public enum DigitType {
        UPPER16,
        LOWER16,
        UPPER32,
        LOWER32
    }

}